package com.cw.demo.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * TODO
 *
 * @author chenw
 * @date 2021/10/11
 */
public class CyclicBarrierDemo1 {
    static class PreTaskThread implements Runnable {
        private String task;
        private CyclicBarrier cyclicBarrier;

        public PreTaskThread(String task, CyclicBarrier cyclicBarrier) {
            this.task = task;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            Random random = new Random();
            try {
                for (int i = 0; i < 4; i++) {
                    Thread.sleep(random.nextInt(1000));
                    System.out.println(task + "任务完成");
                    cyclicBarrier.await();
                }
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
            cyclicBarrier.reset();
        }
    }

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
            System.out.println("本关卡所有前置任务完成，开始游戏。。。");
        });
        new Thread(new PreTaskThread("加载地图", cyclicBarrier)).start();
        new Thread(new PreTaskThread("加载任务模型", cyclicBarrier)).start();
        new Thread(new PreTaskThread("加载背景音乐", cyclicBarrier)).start();
    }
}
